from flask import  Flask,request
from manager_mysql import TodoManagerWithMysql
import json

app = Flask(__name__)
app.config['JSON_AS_ASCII'] = False
manager =TodoManagerWithMysql()


@app.route('/')
def index():
    return '<h1>hello,falsk</h1>'
@app.route('/todos',methods = ['GET'])
def todos():
    if request.args['completed'] == '1':
        return {"todos1": [x.__dict__ for x in manager.get_list() if x.completed]}
    elif request.args['completed'] == '0':
        return {"todos1": [x.__dict__ for x in manager.get_list() if not x.completed]}
    elif request.args['completed'] == 'all':
        return {"todos1": [x.__dict__ for x in manager.get_list()]}
    # return {'todos1':[i.__dict__ for i in manager.get_list()]}
@app.route('/create',methods = ['POST'])
def create_todo():
    # if 'title'not in request.form:
    #     return '参数错误，必须提供title数据'
    # todo = manager.create(request.form['title'])
    # return todo.__dict__
    if 'title' not in request.json:
        return '参数错误，必须提供title数据'
    todo = manager.create(request.json['title'])
    return todo.__dict__

@app.route('/todos/mark_completed',methods=['GET'])
def mark_complete():
    if 'id' not in request.args:
        return '参数错误，必须提供todo_id参数',400
    id = int(request.args['id'])
    todo = manager.mark_completed(id)
    return todo.__dict__
@app.route("/todos/del_id", methods=['GET'])
def del_id():
    if 'id' not in request.args:
        return '参数错误，必须提供 id 参数', 400
    id = int(request.args['id'])
    todo = manager.del_todos(id)
    return todo.__dict__



if __name__ == '__main__':
    app.run(host='127.0.0.1', port=80, debug=True, threaded=True)